<template>
  <div class="detail-container">
    <!-- 左侧：课程详情 -->
    <div class="left-part">
      <div class="course-detail">
        <h1>课程详情</h1>
        <!-- 课程的详细信息展示 -->
        <p>课程名称: {{ course.name }}</p>
        <p>教师: {{ course.teacherId }}</p>
        <p>学分: {{ course.credit }}</p>
        <p>年级: {{ course.grade }}</p>
        <p>时间: {{ course.time }}</p>
        <p>地点: {{ course.location }}</p>
        <p>考试日期: {{ course.examDate }}</p>
        <button class="discussion-button" @click="goToDiscussion">讨论区</button>
        <button class="homework-button" @click="goToHomework">作业栏</button>
        
        <!-- AI 问答部分 -->
        <div class="ai-qa-section">
          <h3>AI 问答</h3>
          <input v-model="userQuestion" type="text" placeholder="输入你的问题..." class="question-input"/>
          <button @click="askAIQuestion" class="ask-ai-btn">提交问题</button>
          <p v-if="aiResponse">AI 回答: {{ aiResponse }}</p>
        </div>
      </div>
    </div>

    <!-- 右侧课程资源部分代码（保持不变） -->
    <div class="right-part">
      <!-- 省略其他部分代码保持简洁 -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as api from "@/api/student/course"; // 假设你有一个 API 模块来获取课程详情
import { useRoute } from 'vue-router'; // 用于获取路由参数

export default {
  name: "CourseManage",
  setup() {
    const route = useRoute(); // 获取当前路由参数
    const courseId = route.params.courseId; // 从路由参数中获取 courseId
    return { courseId }; // 返回给组件使用
  },
  data() {
    return {
      baseURL: "http://localhost:8085", // Base API URL
      course: {}, // 课程详情数据
      courseResources: { name: '课程资源', notes: [] }, // 课程资源数据
      examPapers: { name: '历年试卷库', notes: [] }, // 历年试卷数据
      exerciseBank: { name: '习题库', notes: [] }, // 习题库数据
      selectedFile: null, // 存储用户选择的文件
      id: 1,
      userQuestion: "", // 用户输入的AI问题
      aiResponse: "" // AI返回的回答
    };
  },
  methods: {
    async fetchCourseDetail() {
      const courseId = this.$route.params.courseId;
      const response = await api.getCourseDetail(courseId);
      if (response) {
        this.course = response;
        this.id = this.course.id;
      } else {
        this.$message.error(response.message); // 错误处理
      }
      this.fetchCourseData();
    },
    
    // 跳转讨论区、作业栏
    goToDiscussion() {
      const courseId = this.id;
      this.$router.push({ name: 'Discussion', params: { courseId } });
    },
    goToHomework() {
      const courseId = this.id;
      this.$router.push({ name: 'Homework', params: { courseId } });
    },

    // 处理文件选择
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
      }
    },

    // 上传文件
    uploadFile(endpoint) {
      if (!this.selectedFile) {
        console.error('没有选择文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('courseid', this.courseId);

      axios.post(`${this.baseURL}/courseresource/${endpoint}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then(() => {
        alert("文件上传成功");
        this.selectedFile = null;
        this.fetchCourseData();
      });
    },

    // 下载文件
    downloadFile(fileId) {
      axios.get(`${this.baseURL}/courseresource/download`, {
        params: { 
          fileId: fileId 
        },
        responseType: 'blob'
      })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');

        let fileName = response.headers['content-disposition'].split('filename=')[1].replace(/['"]/g, '');
        
        link.href = url;
        link.setAttribute('download', decodeURIComponent(fileName));
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },

    // 获取课程数据
    fetchCourseData() {
      axios.get(`${this.baseURL}/courseresource/viewware`, { params: { courseId: this.id } })
      .then(response => {
        this.courseResources.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });

      axios.get(`${this.baseURL}/courseresource/viewtest`, { params: { courseId: this.id} })
      .then(response => {
        this.examPapers.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });

      axios.get(`${this.baseURL}/courseresource/viewexercise`, { params: { courseId: this.id } })
      .then(response => {
        this.exerciseBank.notes = response.data.map(item => ({
          title: item.fileName,
          content: item.fileDescription,
          id: item.fileId
        }));
      });
    },

    // 提问AI接口
    async askAIQuestion() {
      if (!this.userQuestion) {
        alert("请输入你的问题！");
        return;
      }

      try {
        const response = await axios.get(`${this.baseURL}/api/baidu/call`, {
          params: { userInput: this.userQuestion }
        });
        
        this.aiResponse = response.data;
      } catch (error) {
        console.error("调用AI接口出错", error);
        this.aiResponse = "调用AI接口时出错，请稍后再试。";
      }
    }
  },

  mounted() {
    this.fetchCourseDetail(); // 获取课程详情
  }
};
</script>

<style scoped>
.detail-container {
  display: flex;
  justify-content: space-between;
}

.left-part {
  width: 28%;
}

.right-part {
  width: 70%;
}

.course-detail {
  padding: 20px;
}

.ai-qa-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f1f1f1;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.question-input {
  width: 80%;
  padding: 5px;
  margin-right: 10px;
}

.ask-ai-btn {
  padding: 5px 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.ask-ai-btn:hover {
  background-color: #388E3C;
}

.ai-response {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>
